"""
余额相关数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Enum
from sqlalchemy.types import DECIMAL
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum

from app.database import Base


class TransactionType(enum.Enum):
    """交易类型枚举"""
    REGISTER_BONUS = "register_bonus"  # 注册奖励
    RECHARGE = "recharge"              # 充值
    CONSUME = "consume"                # 消费
    REFUND = "refund"                  # 退款
    ADMIN_ADJUST = "admin_adjust"      # 管理员调整


class Balance(Base):
    """用户余额表"""
    __tablename__ = "balances"

    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="余额记录ID")
    user_id = Column(Integer, ForeignKey("users.id"), unique=True, nullable=False, comment="用户ID")
    
    # 余额信息
    amount = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment="当前余额")
    frozen_amount = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment="冻结余额")
    total_recharged = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment="累计充值")
    total_consumed = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment="累计消费")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    user = relationship("User", back_populates="balance")

    def __repr__(self):
        return f"<Balance(user_id={self.user_id}, amount={self.amount})>"

    @property
    def available_amount(self):
        """可用余额"""
        return self.amount - self.frozen_amount

    def can_consume(self, amount):
        """检查是否可以消费指定金额"""
        return self.available_amount >= amount


class BalanceTransaction(Base):
    """余额交易记录表"""
    __tablename__ = "balance_transactions"

    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="交易记录ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    
    # 交易信息
    transaction_type = Column(Enum(TransactionType), nullable=False, comment="交易类型")
    amount = Column(DECIMAL(10, 2), nullable=False, comment="交易金额")
    balance_before = Column(DECIMAL(10, 2), nullable=False, comment="交易前余额")
    balance_after = Column(DECIMAL(10, 2), nullable=False, comment="交易后余额")
    
    # 交易描述
    description = Column(String(500), nullable=True, comment="交易描述")
    reference_id = Column(String(100), nullable=True, comment="关联业务ID")
    reference_type = Column(String(50), nullable=True, comment="关联业务类型")
    
    # 外部交易信息（充值时使用）
    external_transaction_id = Column(String(100), nullable=True, comment="外部交易ID")
    payment_method = Column(String(50), nullable=True, comment="支付方式")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    
    # 关联关系
    user = relationship("User", back_populates="balance_transactions")

    def __repr__(self):
        return f"<BalanceTransaction(id={self.id}, user_id={self.user_id}, type={self.transaction_type.value}, amount={self.amount})>"

    @classmethod
    def create_register_bonus(cls, user_id, amount=1.00):
        """创建注册奖励交易记录"""
        return cls(
            user_id=user_id,
            transaction_type=TransactionType.REGISTER_BONUS,
            amount=amount,
            balance_before=0.00,
            balance_after=amount,
            description="新用户注册奖励",
            reference_type="user_registration"
        )

    @classmethod
    def create_monitor_consume(cls, user_id, balance_before, amount=1.00, monitor_id=None):
        """创建监控消费交易记录"""
        return cls(
            user_id=user_id,
            transaction_type=TransactionType.CONSUME,
            amount=-amount,  # 消费为负数
            balance_before=balance_before,
            balance_after=balance_before - amount,
            description="创建监控任务",
            reference_id=str(monitor_id) if monitor_id else None,
            reference_type="monitor_creation"
        )
